<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <div class="table-operator">
      <!-- 搜索板块 -->
      <a-row class="row-item-search">
        <a-form :form="searchForm" class="search-form" layout="inline" @submit="handleSearch">
          <a-form-item label="应用名">
            <a-input v-decorator="['name']" placeholder="请输入应用名"/>
          </a-form-item>
          <a-form-item label="开启状态">
            <a-select v-decorator="['status']" placeholder="请选择开启状态">
              <a-select-option v-for="item in Status.data" :key="item.key" :value="item.key">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="创建时间">
            <a-range-picker
                v-decorator="['between']" format="YYYY-MM-DD HH:mm:ss" show-time
                value-format="YYYY-MM-DD HH:mm:ss"/>
          </a-form-item>
          <a-form-item class="search-btn">
            <a-button html-type="submit" icon="search" type="primary">搜索</a-button>
          </a-form-item>
          <a-form-item class="search-btn">
            <a-button @click="handleReset">重置</a-button>
          </a-form-item>
        </a-form>
      </a-row>
      <!-- 操作板块 -->
      <div class="row-item-tab clearfix">
        <a-button
            v-if="$auth('/pay/app/create')"
            icon="plus"
            type="primary"
            @click="handleCreate()"
        >新增
        </a-button>
      </div>
    </div>
    <s-table
        ref="table"
        :data="loadData"
        :loading="isLoading"
        :pageSize="15"
        :scroll="{ x: 1400, y: '420px', scrollToFirstRowOnChange: true }"
        rowKey="appKey"
    >
      <a-table-column key="appKey" data-index="appKey" title="应用标识"/>
      <a-table-column key="name" align="center" data-index="name" min-width="90" title="应用名"/>
      <a-table-column key="status" align="center" title="开启状态">
        <template #default="record">
          <a-switch
              :checked="record.status === Status.ENABLED.key"
              @change="(checked) => handleStatusChange(record, checked)"
          />
        </template>
      </a-table-column>
      <a-table-column-group title="支付宝配置">
        <a-table-column
            v-for="channel in alipayChannels"
            :key="channel.key"
            :title="channel.name.replace('支付宝', '')"
            align="center"
        >
          <template #default="record">
            <a-button
                v-if="isChannelExists(record.channelCodes, channel.key)"
                shape="circle"
                size="small"
                type="primary"
                @click="openChannelForm(record, channel.key)"
            >
              <a-icon type="check"/>
            </a-button>
            <a-button
                v-else
                shape="circle"
                size="small"
                type="danger"
                @click="openChannelForm(record, channel.key)"
            >
              <a-icon type="close"/>
            </a-button>
          </template>
        </a-table-column>
      </a-table-column-group>
      <a-table-column-group title="微信配置">
        <a-table-column
            v-for="channel in wxChannels"
            :key="channel.key"
            :title="channel.name.replace('微信', '')"
            align="center"
        >
          <template #default="record">
            <a-button
                v-if="isChannelExists(record.channelCodes, channel.key)"
                shape="circle"
                size="small"
                type="primary"
                @click="openChannelForm(record, channel.key)"
            >
              <a-icon type="check"/>
            </a-button>
            <a-button
                v-else
                shape="circle"
                size="small"
                type="danger"
                @click="openChannelForm(record, channel.key)"
            >
              <a-icon type="close"/>
            </a-button>
          </template>
        </a-table-column>
      </a-table-column-group>
      <a-table-column-group title="钱包支付配置">
        <a-table-column
            :title="PayChannelCode.WALLET.name"
            align="center"
        >
          <template #default="record">
            <a-button
                v-if="isChannelExists(record.channelCodes, PayChannelCode.WALLET.key)"
                shape="circle"
                size="small"
                type="primary"
                @click="openChannelForm(record, PayChannelCode.WALLET.key)"
            >
              <a-icon type="check"/>
            </a-button>
            <a-button
                v-else
                shape="circle"
                size="small"
                type="danger"
                @click="openChannelForm(record, PayChannelCode.WALLET.key)"
            >
              <a-icon type="close"/>
            </a-button>
          </template>
        </a-table-column>
      </a-table-column-group>
      <a-table-column-group title="模拟支付配置">
        <a-table-column
            :title="PayChannelCode.MOCK.name"
            align="center"
        >
          <template #default="record">
            <a-button
                v-if="isChannelExists(record.channelCodes, PayChannelCode.MOCK.key)"
                shape="circle"
                size="small"
                type="primary"
                @click="openChannelForm(record, PayChannelCode.MOCK.key)"
            >
              <a-icon type="check"/>
            </a-button>
            <a-button
                v-else
                shape="circle"
                size="small"
                type="danger"
                @click="openChannelForm(record, PayChannelCode.MOCK.key)"
            >
              <a-icon type="close"/>
            </a-button>
          </template>
        </a-table-column>
      </a-table-column-group>
      <a-table-column key="action" fixed="right" title="操作">
        <template #default="record">
        <span>
          <a class="mr-5" @click="handleEdit(record)">编辑</a>
          <a @click="handleDelete(record)">删除</a>
        </span>
        </template>
      </a-table-column>
    </s-table>
    <Form ref="Form" @handleSubmit="handleRefresh"/>
    <ChannelForm ref="channelForm" @handleSubmit="handleRefresh"/>
    <AlipayChannelForm ref="alipayChannelForm" @handleSubmit="handleRefresh"/>
    <WechatChannelForm ref="wechatChannelForm" @handleSubmit="handleRefresh"/>
  </a-card>
</template>

<script>
import * as Api from '@/api/pay/app'
import {STable} from '@/components/Table'
import TransactionStatusEnum from "@/common/enum/points/TransactionStatus";
import Form from './components/Form'
import ChannelForm from './components/ChannelForm'
import AlipayChannelForm from './components/AlipayChannelForm'
import WechatChannelForm from './components/WechatChannelForm'
import StatusEnum from '@/common/enum/Status'
import PayChannelCodeEnum from '@/common/enum/pay/PayChannelCodeEnum'

export default {
  name: 'Index',
  components: {
    STable,
    Form,
    ChannelForm,
    AlipayChannelForm,
    WechatChannelForm
  },
  data() {
    return {
      // 交易状态枚举
      TransactionStatusEnum,
      // 当前表单元素
      searchForm: this.$form.createForm(this),
      // 查询参数
      queryParam: {},
      // 正在加载
      isLoading: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: param => {
        return Api.page({...param, ...this.queryParam})
            .then(response => response)
      },
      alipayChannels: [
        PayChannelCodeEnum.ALIPAY_APP,
        PayChannelCodeEnum.ALIPAY_PC,
        PayChannelCodeEnum.ALIPAY_WAP,
        PayChannelCodeEnum.ALIPAY_QR,
        PayChannelCodeEnum.ALIPAY_BAR
      ],
      wxChannels: [
        PayChannelCodeEnum.WX_LITE,
        PayChannelCodeEnum.WX_PUB,
        PayChannelCodeEnum.WX_APP,
        PayChannelCodeEnum.WX_NATIVE,
        PayChannelCodeEnum.WX_WAP,
        PayChannelCodeEnum.WX_BAR
      ]
    }
  },
  computed: {
    Status() {
      return StatusEnum
    },
    PayChannelCode() {
      return PayChannelCodeEnum
    }
  },
  methods: {
    // 新增记录
    handleCreate() {
      this.$refs.Form.show()
    },

    // 编辑记录
    handleEdit(record) {
      this.$refs.Form.show(record)
    },

    // 删除记录
    handleDelete(record) {
      const that = this
      const modal = this.$confirm({
        title: '您确定要删除该应用吗?',
        content: '删除后不可恢复，请谨慎操作',
        onOk() {
          return Api.deleted(record.id)
              .then(result => {
                that.$message.success("操作成功", 1.5)
                that.handleRefresh()
              })
              .catch(() => true)
              .finally(result => modal.destroy())
        }
      })
    },

    handleStatusChange(record, checked) {
      let status = checked ? this.Status.ENABLED : this.Status.DISABLED
      const that = this
      const modal = this.$confirm({
        title: '确认要"' + status.name + '""' + record.name + '"应用吗?',
        content: '操作后不可恢复，请谨慎操作',
        onOk() {
          return Api.changeAppStatus(record.id, status.key)
              .then(result => {
                that.$message.success("操作成功", 1.5)
                that.handleRefresh()
              })
              .finally(result => modal.destroy())
        }
      })
    },

    isChannelExists(channels, channelCode) {
      if (!channels) {
        return false
      }
      return channels.indexOf(channelCode) !== -1
    },
    openChannelForm(record, payCode) {
      // channelParam.appId = record.id
      // channelParam.payCode = payCode
      if (payCode.indexOf('ALIPAY_') === 0) {
        this.$refs.alipayChannelForm.show(record.id, payCode)
        return
      }
      if (payCode.indexOf('WX_') === 0) {
        this.$refs.wechatChannelForm.show(record.id, payCode)
        return
      }
      if (payCode.indexOf('MOCK') === 0 || payCode.indexOf('WALLET') === 0) {
        this.$refs.channelForm.show(record.id, payCode)
      }
    },
    /**
     * 刷新列表
     * @param {Boolean} bool 强制刷新到第一页
     */
    handleRefresh(bool = false) {
      this.$refs.table.refresh(bool)
    },

    // 确认搜索
    handleSearch(e) {
      e.preventDefault()
      this.searchForm.validateFields((error, values) => {
        if (!error) {
          this.queryParam = {...this.queryParam, ...values}
          this.handleRefresh(true)
        }
      })
    },

    // 重置搜索表单
    handleReset() {
      this.searchForm.resetFields()
    }

  }
}
</script>

<style lang="less" scoped>
.ant-card-body {
  padding: 22px 29px 25px;
}
</style>
